package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.respons.FlowDetailRs;
import com.xmy.cultivate.service.IAuditFlowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.Result;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xmy.cultivate.entity.AuditFlow;
import com.xmy.cultivate.mapper.AuditFlowMapper;
import com.xmy.cultivate.respons.FlowRs;
import com.xmy.cultivate.respons.FlowTeacherRs;
import com.xmy.cultivate.service.IAuditFlowDetailService;
import com.xmy.cultivate.service.IAuditFlowSetProcessService;
import com.xmy.cultivate.service.IAuditFlowSetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 实例审核流程详情 服务实现类
 * </p>
 *
 * @author hpiggy
 * @since 2025-01-01
 */
@Service
public class AuditFlowServiceImpl extends ServiceImpl<AuditFlowMapper, AuditFlow> implements IAuditFlowService {


    @Autowired
    @Lazy
    IAuditFlowSetProcessService iAuditFlowSetProcessService;

    @Autowired
    @Lazy
    IAuditFlowSetService iAuditFlowSetService;

    @Autowired
    @Lazy
    StaffMapper staffMapper;

    @Autowired
    @Lazy
    IAuditFlowDetailService iAuditFlowDetailService;

    @Autowired
    @Lazy
    private AuditFlowDetailMapper auditFlowDetailMapper;

    @Autowired
    @Lazy
    AuditFlowSetProcessMapper auditFlowSetProcessMapper;

    @Autowired
    @Lazy
    AuditClaimMapper auditClaimMapper;

    /**
     *前端页面添加数据时调用
     * @param flowId 流程id
     * @param schoolId 校区id
     * @param departId 部门id
     */
    @Override
    public List<FlowRs> getFlowTask(Long flowId, Long schoolId, Long departId, Long adminId){

        Integer versionNum = auditFlowSetProcessMapper.getMaxVersionnNum(flowId);//获取出最大的版本号

        QueryWrapper<AuditFlowSetProcess> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("flow_id",flowId);
        queryWrapper.eq("version_num",versionNum);
        queryWrapper.orderByAsc("step_num");
        List<AuditFlowSetProcess> auditFlowSetProcessList = iAuditFlowSetProcessService.list(queryWrapper);
        QueryWrapper<AuditFlowSet> auditFlowSetQueryWrapper = new QueryWrapper<>();
        List<FlowRs> flowRsList = new ArrayList<>();
        for (AuditFlowSetProcess auditFlowSetProcess : auditFlowSetProcessList) {
            auditFlowSetQueryWrapper.clear();
            auditFlowSetQueryWrapper.eq("flow_id",flowId);
            auditFlowSetQueryWrapper.eq("step_num",auditFlowSetProcess.getStepNum());
            auditFlowSetQueryWrapper.eq("version_num",auditFlowSetProcess.getVersionNum());
            if (auditFlowSetProcess.getType().equals(1)){
                //按校区
                if (schoolId == null){
                    schoolId = 0L;
                }
                auditFlowSetQueryWrapper.eq("school_id",schoolId);
            }else if (auditFlowSetProcess.getType().equals(2)){
                //按部门
                if (departId == null){
                    departId = 0L;
                }
                auditFlowSetQueryWrapper.eq("depart_id",departId);
                //按部门
            }else if (auditFlowSetProcess.getType().equals(3)){
                //按校区和部门
                //auditFlowSetQueryWrapper.and(i->i.eq("school_id",schoolId).or(j->j.eq("depart_id",departId)));
            }
            auditFlowSetQueryWrapper.orderByAsc("step_num");
            auditFlowSetQueryWrapper.last("limit 1");
            AuditFlowSet auditFlowSet = iAuditFlowSetService.getOne(auditFlowSetQueryWrapper);
            FlowRs flowRs = new FlowRs();
            if (auditFlowSet!=null){
                flowRs.setId(auditFlowSet.getId());
                flowRs.setName(auditFlowSet.getName());
                if (auditFlowSet.getType().equals(0)){
                    //发起人
                    List<FlowTeacherRs> flowTeacherRsList = staffMapper.getFlowTeacherList(adminId.toString());
                    flowRs.setTeacherList(flowTeacherRsList);
                }else {
                    if (auditFlowSet.getCheckIds()!=null){
                        List<FlowTeacherRs> flowTeacherRsList = staffMapper.getFlowTeacherList(auditFlowSet.getCheckIds());
                        flowRs.setTeacherList(flowTeacherRsList);
                    }
                }
                flowRsList.add(flowRs);
            }
        }
        return flowRsList;
    }





    /**
     * 保存数据时调用
     * @param flowId
     * @param schoolId
     * @param departId
     * @return
     */
    @Override
    public List<AuditFlowSet> getFlowTaskForAdd(Long flowId, Long schoolId, Long departId, Long adminId){

        Integer versionNum = auditFlowSetProcessMapper.getMaxVersionnNum(flowId);//获取出最大的版本号

        QueryWrapper<AuditFlowSetProcess> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("flow_id",flowId);
        queryWrapper.eq("version_num",versionNum);
        queryWrapper.orderByAsc("step_num");
        //获取审批的流程步骤
        List<AuditFlowSetProcess> auditFlowSetProcessList = iAuditFlowSetProcessService.list(queryWrapper);
        QueryWrapper<AuditFlowSet> auditFlowSetQueryWrapper = new QueryWrapper<>();
        List<AuditFlowSet> auditFlowSetList = new ArrayList<>();
        for (AuditFlowSetProcess auditFlowSetProcess : auditFlowSetProcessList) {
            auditFlowSetQueryWrapper.clear();
            auditFlowSetQueryWrapper.eq("flow_id",flowId);
            auditFlowSetQueryWrapper.eq("step_num",auditFlowSetProcess.getStepNum());
            auditFlowSetQueryWrapper.eq("version_num",auditFlowSetProcess.getVersionNum());
            if (auditFlowSetProcess.getType().equals(1)){
                //按校区
                if (schoolId == null){
                    schoolId = 0L;
                }
                auditFlowSetQueryWrapper.eq("school_id",schoolId);
            }else if (auditFlowSetProcess.getType().equals(2)){
                //按部门
                if (departId == null){
                    departId = 0L;
                }
                auditFlowSetQueryWrapper.eq("depart_id",departId);
                //按部门
            }else if (auditFlowSetProcess.getType().equals(3)){
                //按校区和部门
            }
            auditFlowSetQueryWrapper.orderByAsc("step_num");
            auditFlowSetQueryWrapper.last("limit 1");
            AuditFlowSet auditFlowSet = iAuditFlowSetService.getOne(auditFlowSetQueryWrapper);
            //当前步骤是否设置过
            if (auditFlowSet!=null){
                if (auditFlowSet.getType().equals(0)){
                    //发起人
                    List<FlowTeacherRs> flowTeacherRsList = staffMapper.getFlowTeacherList(adminId.toString());
                    auditFlowSet.setTeacherList(flowTeacherRsList);
                }else {
                    if (auditFlowSet.getCheckIds()!=null){
                        List<FlowTeacherRs> flowTeacherRsList = staffMapper.getFlowTeacherList(auditFlowSet.getCheckIds());
                        auditFlowSet.setTeacherList(flowTeacherRsList);
                    }
                }
                auditFlowSetList.add(auditFlowSet);
            }
        }
        return auditFlowSetList;
    }


    @Override
    public FlowDetailRs getFlowTaskForDetail(Long sourseId){
        FlowDetailRs flowDetailRs = iAuditFlowDetailService.getFlowDetailBySourseId(sourseId);
        return  flowDetailRs;
    }





    /**
     * 添加实例流程
     * @param sourseId
     * @param flowId
     * @param schoolId
     * @param departId
     * @return
     */
    @Override
    public boolean addFlowTask(Long sourseId, Long flowId, Long schoolId, Long departId,Long adminId){
        AuditClaim auditClaim = auditClaimMapper.getClaimOneByIdDesc(sourseId);
        if (auditClaim == null){
            return false;
        }
        Integer sourseVersionNum = auditClaim.getVersionNum();

        List<AuditFlowSet> flowRsList = getFlowTaskForAdd(flowId,schoolId,departId,adminId);
        Integer count = auditFlowDetailMapper.getVersionCount(sourseId,sourseVersionNum);
        if (count == 0){
            AuditFlowDetail auditFlowDetail;
            Integer arriveStep = null;
            for (AuditFlowSet flowRs : flowRsList){
                //设置第一个审批步骤（即当前到了哪个步骤审批）
                if (arriveStep == null){
                    if (flowRs.getType().equals(1)){
                        arriveStep = flowRs.getStepNum();
                    }
                }
                List<FlowTeacherRs> flowTeacherRsList = flowRs.getTeacherList();
                //发起人
                if (flowRs.getType().equals(0)){
                    //创建人
                    auditFlowDetail = new AuditFlowDetail();
                    //auditFlowDetail.setId();
                    auditFlowDetail.setFlowId(flowRs.getFlowId());
                    auditFlowDetail.setSourseId(sourseId);
                    auditFlowDetail.setStepNum(flowRs.getStepNum());
                    auditFlowDetail.setCheckNum(flowRs.getCheckNum());
                    auditFlowDetail.setName(flowRs.getName());
                    auditFlowDetail.setSchoolId(schoolId);
                    auditFlowDetail.setType(flowRs.getType());
                    auditFlowDetail.setIsArrive(1);
                    auditFlowDetail.setArriveDateTime(LocalDateTime.now().withNano(0));
                    auditFlowDetail.setOperateDateTime(LocalDateTime.now().withNano(0));
                    auditFlowDetail.setCheckId(auditClaim.getCreatedId());
                    auditFlowDetail.setSourseVersionNum(sourseVersionNum);
                    //添加当前实例的审批流程
                    iAuditFlowDetailService.save(auditFlowDetail);
                }else {
                    for (FlowTeacherRs flowTeacherRs : flowTeacherRsList){
                        auditFlowDetail = new AuditFlowDetail();
                        //auditFlowDetail.setId();
                        auditFlowDetail.setFlowId(flowRs.getFlowId());
                        auditFlowDetail.setSourseId(sourseId);
                        auditFlowDetail.setStepNum(flowRs.getStepNum());
                        auditFlowDetail.setCheckNum(flowRs.getCheckNum());
                        auditFlowDetail.setName(flowRs.getName());
                        auditFlowDetail.setSchoolId(schoolId);
                        auditFlowDetail.setType(flowRs.getType());
                        auditFlowDetail.setCheckId(flowTeacherRs.getId());
                        auditFlowDetail.setSourseVersionNum(sourseVersionNum);
                        //第一个审批人
                        if (arriveStep!=null){
                            if (flowRs.getStepNum() <= arriveStep){
                                auditFlowDetail.setIsArrive(1);
                                auditFlowDetail.setArriveDateTime(LocalDateTime.now().withNano(0));
                            }
                        }
                        //添加当前实例的审批流程
                        iAuditFlowDetailService.save(auditFlowDetail);
                    }
                }
            }
            auditClaim.setArriveStep(arriveStep);
            auditClaim.setStepNum(arriveStep);
            auditClaimMapper.updateById(auditClaim);
        }
        return true;
    }

    /**
     * 审批通过
     * @param sourseId audit_claimg表的id
     * @param teacherId 登陆人id
     * @return
     */
    @Transactional
    @Override
    public Result completeTask(Long sourseId,Long teacherId){
        return taskDo(sourseId,teacherId,1);
    }

    /**
     *审批拒绝
     * @param sourseId audit_claimg表的id
     * @param teacherId 登陆人id
     * @return
     */
    @Override
    public Result refuseTask(Long sourseId,Long teacherId){
        return taskDo(sourseId,teacherId,2);
    }

    /**
     *
     * @param sourseId
     * @param teacherId
     * @param status 1通过，2拒绝
     * @return
     */
    @Override
    public Result taskDo(Long sourseId, Long teacherId, Integer status){
        AuditClaim auditClaim =  auditClaimMapper.getClaimOneByIdDesc(sourseId);
        if (auditClaim == null){
            return new Result(Code.ERROR,"","申请数据不存在");
        }

        AuditFlowDetail auditFlowDetail = auditFlowDetailMapper.getFlowDetailOne(sourseId,teacherId,auditClaim.getStepNum(),auditClaim.getVersionNum(),1);
        if (auditFlowDetail != null){
            if (!auditFlowDetail.getStatus().equals(0)){
                //已审核
                return new Result(Code.OK,"","审核成功");
            }
            /*if (auditClaim.getArriveStep() != auditFlowDetail.getStepNum()){
                //还不到处理
                return new Result(Code.ERROR,"","还未到您审核");
            }*/
        }else {
            //数据不存在
            return new Result(Code.ERROR,"","该数据无需您审核");
        }

        auditFlowDetail.setOperateDateTime(LocalDateTime.now().withNano(0));
        auditFlowDetail.setStatus(status);
        if (status.equals(1)){
            //QueryWrapper<AuditFlowSetProcess> queryWrapper = new QueryWrapper<>();
            //queryWrapper.eq("flow_id",auditFlowDetail.getFlowId());
            //queryWrapper.eq("step_num",auditFlowDetail.getStepNum());

            /**
             * 下一流程审批人
             */
            AuditFlowDetail auditFlowDetailNext = auditFlowDetailMapper.getNextFlowDetail(sourseId,auditClaim.getVersionNum(),auditFlowDetail.getStepNum(),1);
            if (auditFlowDetailNext != null){
                auditClaim.setStepNum(auditFlowDetailNext.getStepNum());
                auditClaim.setArriveStep(auditFlowDetailNext.getStepNum());
                auditFlowDetailNext.setIsArrive(1);
                auditFlowDetailNext.setArriveDateTime(LocalDateTime.now().withNano(0));
                auditFlowDetailMapper.updateById(auditFlowDetailNext);
            }else {
                //不存在下一个流程，所有流程都通过
                auditClaim.setStatus(status);
            }

            //抄送
            AuditFlowDetail auditFlowDetailCarbon = auditFlowDetailMapper.getNextFlowDetail(sourseId,auditClaim.getVersionNum(),auditFlowDetail.getStepNum(),2);
            if (auditFlowDetailCarbon != null){
                UpdateWrapper<AuditFlowDetail> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("flow_id",auditFlowDetailCarbon.getFlowId());
                updateWrapper.eq("sourse_id",auditFlowDetailCarbon.getSourseId());
                updateWrapper.eq("step_num",auditFlowDetailCarbon.getStepNum());
                updateWrapper.eq("sourse_version_num",auditFlowDetailCarbon.getSourseVersionNum());
                updateWrapper.set("is_arrive",1);
                updateWrapper.set("arrive_date_time",LocalDateTime.now().withNano(0));
                auditFlowDetailMapper.update(null, updateWrapper);
            }

        }else {
            auditClaim.setStatus(status);
        }
        auditClaimMapper.updateById(auditClaim);
        //if (auditClaim.getStepNum())
        iAuditFlowDetailService.updateById(auditFlowDetail);
        return new Result(Code.OK,"","审核成功");
    }
}
